package com.live.proxy.home;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.live.proxy.R;
import com.live.proxy.model.InteThaliModel;
import com.live.proxy.model.OrderModel;
import com.live.proxy.model.UserModel;
import com.live.proxy.sql.UserDatabase;
import com.live.proxy.tool.GetUtil;
import com.live.proxy.tool.InteThaliArrayAdapter;
import com.live.proxy.tool.OkHttpUtils;
import com.live.proxy.tool.StatusBarUtils;
import com.live.proxy.view.ToastUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

public class IntegralPayActivity extends AppCompatActivity {
    ImageButton integral_pay_back;
    RecyclerView integral_pay_recyclerview;
    TextView integral_pay_add;

    UserDatabase userDb;
    UserModel userModel;
    List<OrderModel> list = new ArrayList<>();
    List<InteThaliModel> inteThaliList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_integral_pay);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);

        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();

        integral_pay_back = findViewById(R.id.integral_pay_back);
        integral_pay_recyclerview = findViewById(R.id.integral_pay_recyclerview);
        integral_pay_add = findViewById(R.id.integral_pay_add);

        integral_pay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //添加
        integral_pay_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_order_add();
            }
        });
        //加载订单
        reloadOrderList();
    }
    public void reloadOrderList(){
        //加载订单列表
        try {
            getAccount(GetUtil.getOrderList(),"",userModel.getToken(),1);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //新增订单
    public void dialog_order_add(){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(false);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_order_add);

        final AppCompatSpinner dialog_orderadd_intethali = window.findViewById(R.id.dialog_orderadd_intethali);
        final TextView dialog_orderadd_title = window.findViewById(R.id.dialog_orderadd_title);
        final TextView dialog_orderadd_no = window.findViewById(R.id.dialog_orderadd_no);
        final TextView dialog_orderadd_ok = window.findViewById(R.id.dialog_orderadd_ok);

        final int[] selectThaliPositon = {-1};
        //套餐列表
        InteThaliArrayAdapter thaliAdapter = new InteThaliArrayAdapter(getApplicationContext(), inteThaliList,15);
        dialog_orderadd_intethali.setAdapter(thaliAdapter);
        dialog_orderadd_intethali.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //获取Spinner控件的适配器
                selectThaliPositon[0] = position;
                dialog_orderadd_title.setText("已选择："+inteThaliList.get(position).getInteName()+"，金额："+inteThaliList.get(position).getPrice());
                if(adapter != null){
                    adapter.notifyDataSetChanged();
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                //没有选中时的处理
            }
        });

        dialog_orderadd_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog_orderadd_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(selectThaliPositon[0] == -1){
                    ToastUtils.Setinfo(getApplicationContext(),"请选择套餐！",2);
                    return;
                }
                try {
                    JSONObject json = new JSONObject();
                    json.put("app_id",userModel.getAppId());
                    json.put("inte_id",inteThaliList.get(selectThaliPositon[0]).getInteId());
                    getAccount(GetUtil.createOrder(),json.toString(),userModel.getToken(),3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    //选择：套餐续费、AI问答加购、AI训练加购
    public void dialog_order_operate(int position){
        final AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();//这里要添加window  这才是重点
        window.setContentView(R.layout.dialog_order_operate);
        final TextView dialog_order_cancel = window.findViewById(R.id.dialog_order_cancel);
        final TextView dialog_order_delete = window.findViewById(R.id.dialog_order_delete);

        dialog_order_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    JSONObject json = new JSONObject();
                    json.put("order_no",list.get(position).getOrderNo());
                    getAccount(GetUtil.cancelOrder(),json.toString(),userModel.getToken(),3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
        dialog_order_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    JSONObject json = new JSONObject();
                    json.put("order_no",list.get(position).getOrderNo());
                    getAccount(GetUtil.deleteOrder(),json.toString(),userModel.getToken(),3);
                }catch (Exception e){
                    e.printStackTrace();
                }
                dialog.dismiss();
            }
        });
    }
    private MyAdapter adapter;
    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder holder = new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_order, parent, false));
            return holder;
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;
            OrderModel orderModel = list.get(position);

            mholder.item_order_orderno.setText(orderModel.getOrderNo());
            mholder.item_order_inte_name.setText(orderModel.getInteThaliName());
            //1预订单,2已支付,3已取消
            switch (orderModel.getOrderStatus()){
                case 1:mholder.item_order_status.setText("预订单");mholder.item_order_status.setTextColor(Color.GREEN);break;
                case 2:mholder.item_order_status.setText("已支付");mholder.item_order_status.setTextColor(Color.BLUE);break;
                case 3:mholder.item_order_status.setText("已取消");mholder.item_order_status.setTextColor(Color.RED);break;
            }
            mholder.item_order_amount.setText(orderModel.getOrderAmount()+"元");
            mholder.item_order_create_time.setText(orderModel.getCreateTime());
            //删除
            mholder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog_order_operate(position);
                }
            });
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public int getItemCount() {
            return list.size();
        }
        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_order_orderno;
            TextView item_order_inte_name;
            TextView item_order_status;
            TextView item_order_amount;
            TextView item_order_create_time;
            public MyViewHolder( View itemView) {
                super(itemView);
                item_order_orderno = itemView.findViewById(R.id.item_order_orderno);
                item_order_inte_name = itemView.findViewById(R.id.item_order_inte_name);
                item_order_status = itemView.findViewById(R.id.item_order_status);
                item_order_amount = itemView.findViewById(R.id.item_order_amount);
                item_order_create_time = itemView.findViewById(R.id.item_order_create_time);
            }
        }
    }

    public static int REQUEST_STATUS = 0;
    public static final int RRQUEST_FAILURE = 1;
    public static final int RRQUEST_SUCCESS = 2;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RRQUEST_FAILURE:
                    ToastUtils.Setinfo(getApplicationContext(),msg.obj.toString(),2);
                    break;
                case RRQUEST_SUCCESS:
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if(json.getInt("code") == 1){
                            switch (REQUEST_STATUS){
                                case 1://获取列表
                                    list.clear();
                                    JSONArray dataJson = json.getJSONArray("data");
                                    for (int i = 0 ; i < dataJson.length() ;i++){
                                        JSONObject inteJson = dataJson.getJSONObject(i);
                                        OrderModel model = new OrderModel();
                                        model.setOrderNo(inteJson.getString("order_no"));
                                        model.setInteThaliName(inteJson.getString("inte_thali_name"));
                                        model.setOrderStatus(inteJson.getInt("order_status"));
                                        model.setOrderAmount(inteJson.getInt("order_amount"));
                                        model.setCreateTime(inteJson.getString("create_time"));
                                        list.add(model);
                                    }
                                    adapter = new MyAdapter();
                                    integral_pay_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
                                    integral_pay_recyclerview.setAdapter(adapter);

                                    if(inteThaliList.size() == 0){
                                        //获取积分套餐列表
                                        JSONObject appJson = GetUtil.getAppInfo(getApplicationContext());
                                        getAccount(GetUtil.getInteThaliList(),appJson.toString(),userModel.getToken(),2);
                                    }
                                    break;
                                case 2://获取积分套餐
                                    JSONArray thalisArray = json.getJSONArray("data");
                                    for (int i = 0 ; i < thalisArray.length() ;i++){
                                        JSONObject thalisJson = thalisArray.getJSONObject(i);
                                        InteThaliModel model = new InteThaliModel();
                                        model.setInteId(thalisJson.getInt("inte_id"));
                                        model.setInteName(thalisJson.getString("inte_thali_name"));
                                        model.setRate(thalisJson.getString("rate"));
                                        model.setPrice(thalisJson.getInt("price"));
                                        inteThaliList.add(model);
                                    }
                                    break;
                                case 3://新增订单、取消订单、删除订单
                                    ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),1);
                                    //加载订单
                                    reloadOrderList();
                                    break;
                            }
                        }else{
                            ToastUtils.Setinfo(getApplicationContext(),json.getString("info"),2);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };
    public void getAccount(String url,String jsonStr,String token,int STATUS){
        OkHttpUtils.sendOkHttpJsonTokenRequest(url, jsonStr,new okhttp3.Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = new Message();
                message.what = RRQUEST_FAILURE;
                message.obj = "【请求异常】请联系管理员";
                handler.sendMessage(message);
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                REQUEST_STATUS = STATUS;
                String responseData = response.body().string();
                Message message = new Message();
                message.what = RRQUEST_SUCCESS;
                message.obj = responseData;
                handler.sendMessage(message);
            }
        },token);
    }
}